<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>客户端</title>
  <!-- 引入layui -->
  <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
  <script src="https://www.layuicdn.com/layui/layui.js"></script>
  <style>
    .modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #000;
    }

    .login-container {
      width: 500px;
      height: 400px;
      background-color: #124e70;
      color: #c2c2c2;
      border-radius: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
    }

    .login-container input {
      width: 100%;
      height: 30px;
      margin-bottom: 10px;
      border-radius: 5px;
      border: 1px solid #8c8c8c;
      box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
    }

    .login-container button {
      width: 100px;
      height: 30px;
      border: 1px solid #8c8c8c;
      text-align: center;
      margin-top: 20px;
      line-height: 30px;
      cursor: pointer;
      box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
      border-radius: 5px;
    }
  </style>
</head>

<body>
  <div id="app">
    <h1>当前登录ID: <span id="currentId"></span> </h1>
    <div class="layui-form-item">
      <input type="text" id="messageInput" placeholder="请输入消息" class="layui-input">
    </div>
    <button class="layui-btn" onclick="sendMessage()">发送</button>
    <button class="layui-btn" onclick="sendAllNoMe()">广播消息给所有客户端 不包含自己</button>
    <button class="layui-btn" onclick="broadcastUserList()">广播 包含自己</button>

    <!-- 用户选择列表 -->
    <div class="layui-form">
      <select id="userSelect" multiple placeholder="请选择用户">
      </select>
    </div>

    <div>
      收到的消息<h1 id="messages"></h1>
    </div>

    <div class="modal" id="loginModal">
      <div class="login-container">
        <h2 style="margin-bottom: 20px;">websocket 登录</h2>
        <div class="layui-form-item">
          <input type="text" id="loginId" placeholder="请输入登录ID" class="layui-input">
        </div>
        <div class="layui-form-item">
          <input type="text" id="loginAddress" placeholder="请输入连接地址" class="layui-input">
        </div>
        <button class="layui-btn" onclick="login()">登录</button>
      </div>
    </div>
  </div>

  <script>
    let ws = null;
    let reconnectAttempts = 0;
    const maxReconnectAttempts = 5;
    const reconnectInterval = 3000;
    let userList = [];

    function login() {
      connect();
    }

    function connect() {
      const loginAddress = document.getElementById('loginAddress').value;
      ws = new WebSocket(loginAddress);

      ws.onopen = () => {
        console.log("WebSocket连接成功");
        reconnectAttempts = 0;
        const loginId = document.getElementById('loginId').value;
        document.getElementById('currentId').textContent = loginId;
        ws.send(JSON.stringify({
          "id": loginId,
          "login": true,
        }));
      }

      ws.onclose = (e) => {
        console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean)
        if (reconnectAttempts < maxReconnectAttempts) {
          setTimeout(() => {
            reconnectAttempts++;
            connect();
          }, reconnectInterval);
        } else {
          console.log("重连次数超过最大限制,停止重连");
        }
      }

      ws.onerror = (err) => {
        console.error("WebSocket发生错误:", err);
      }

      ws.onmessage = (e) => {
        console.log(e, "eeee-");
        try {
          const data = JSON.parse(e.data);
          if (data.type === 'error') {
            reconnectAttempts = maxReconnectAttempts;
            document.getElementById('loginModal').style.display = 'block';
            layer.msg(data.message);
          } else {
            handleMessage(e.data);
            if (!data.type || data.type !== 'error') {
              document.getElementById('loginModal').style.display = 'none';
            }
          }
        } catch (err) {
          handleMessage(e.data);
          document.getElementById('loginModal').style.display = 'none';
        }
      }
    }

    function handleMessage(data) {
      const info = JSON.parse(data);
      if (info?.type === 'error') {
        layer.msg(info.message);
      } else if (info?.type === 'userList') {
        userList = info.users;
        updateUserSelect();
      } else {
        console.log(info, "info");
        document.getElementById('messages').textContent = info.message;
      }
    }

    function updateUserSelect() {
      const select = document.getElementById('userSelect');
      select.innerHTML = '';
      userList.forEach(user => {
        const option = document.createElement('option');
        option.value = user;
        option.text = user; // 添加text属性显示选项文本
        select.appendChild(option);
      });
      // 重新渲染layui表单
      layui.form.render('select');
    }

    function sendMessage() {
      const select = document.getElementById('userSelect');
      const selectedUsers = Array.from(select.selectedOptions).map(option => option.value);

      if (selectedUsers.length === 0) {
        layer.msg("请选择用户");
        return;
      }

      if (ws.readyState === WebSocket.OPEN) {
        const messageInput = document.getElementById('messageInput').value;
        const loginId = document.getElementById('loginId').value;

        selectedUsers.forEach(user => {
          ws.send(JSON.stringify({
            "id": loginId,
            "login": false,
            "to": user,
            "message": messageInput
          }));
        });
      } else {
        layer.msg("WebSocket未连接,消息发送失败");
      }
    }

    function sendAllNoMe() {
      if (ws.readyState === WebSocket.OPEN) {
        const messageInput = document.getElementById('messageInput').value;
        const loginId = document.getElementById('loginId').value;

        ws.send(JSON.stringify({
          "id": loginId,
          "login": false,
          "type": "allNoMe",
          "message": messageInput
        }));
      } else {
        layer.msg("WebSocket未连接,消息发送失败");
      }
    }

    function broadcastUserList() {
      const messageInput = document.getElementById('messageInput').value;
      const loginId = document.getElementById('loginId').value;

      ws.send(JSON.stringify({
        'type': 'all',
        "login": false,
        'message': messageInput,
        'id': loginId,
      }));
    }
    window.onbeforeunload = function () {
      ws.close();
    }  
  </script>
</body>

</html>